package com.db.ionio.serialization;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;

/**
 * @author Alexander Kotov (kotov.alex.22@gmail.com)
 */
public class SerializationServer {
    private final int port;
    private final Map<String, Serializer<SensorData[]>> serializers = SerializationClient.getAllSirializers();

    public SerializationServer(int port) {
        this.port = port;
    }

    public void run() {
        while (true){
            System.out.println("Waiting for client connection...");
            try(ServerSocket serverSocket = new ServerSocket(port);
                Socket socket = serverSocket.accept();
                PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
                InputStream inputStream = socket.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()))){
                String type = null;
                while ((type = reader.readLine()) == null);
                //String type = reader.readLine();

                if (serializers.containsKey(type)) {
                    Serializer <SensorData[]> objectSerializer = serializers.get(type);
                    System.out.println("Use " + type + " serializer");
                    SensorData[] sensorDataBatch = objectSerializer.deserialize(inputStream);
                    System.out.println("Received " + sensorDataBatch.length + " elements");
                    double avgElevation = 0;
                    for (SensorData sensorData : sensorDataBatch) {
                        avgElevation += sensorData.getElevation();
                    }
                    avgElevation /= sensorDataBatch.length;
                    System.out.println("Average elevation is " + avgElevation);
                } else {
                    writer.println("Unexpexted serialize type '" + type + "'");
                    System.out.println("Unexpexted serialize type '" + type + "'");
                }
                writer.println("done");
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
